package com.lindenvalley.ch.network;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.lindenvalley.ch.R;
import com.lindenvalley.ch.content.Task;
import com.lindenvalley.ch.content.User;

public class OnlineTaskFactory implements TaskInterface {

	@Override
	public void saveTask(final Context mContext, final Task savedTask) {
		
		final WorkServer server = WorkServer.getInstance();
		final User user = server.getUser();
		final Task mTask = savedTask;
		if (mTask != null) {
			String action = null;
			if (mTask.getTaskId() == 0) {
				action = WorkServer.TASK_ADD;
			} else {
				action = WorkServer.TASK_UPDATE;
			}
			
			AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>(){
				
				ProgressDialog dialog;
				boolean isCancel = false;
				String actionTask;
				
				@Override
				protected void onPreExecute (){
					dialog = new ProgressDialog(mContext);
					dialog.setMessage(mContext.getString(R.string.savingData));						
					dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
						
						@Override
						public void onCancel(DialogInterface dialog) {
							isCancel = true;
						}
					});
					dialog.show();
					
				}

				@Override
				protected Object doInBackground(Object... params) {
					// TODO Auto-generated method stub
					String result = null;
					if (params != null && params.length > 0) {
						actionTask = (String) params[0];
						result = server.doTask(actionTask,mTask, user);
						Log.i("!!!!", "TASK RESULT " + result);
						
					}
					return result;
				}
				
				@Override 
				protected void onPostExecute(Object result) {
			         if (dialog != null && dialog.isShowing()){
			        	 dialog.dismiss();
			         }
			        	 
			         if (!isCancel){
				         if (result instanceof String && result != null){
				        	 if (WorkServer.DENY_VALUE.equals(result)){
				        		 Toast.makeText(mContext, R.string.updateFail, Toast.LENGTH_SHORT).show();
				        	 } else if (WorkServer.NOT_CONNECT.equals(result)){
				        		 Toast.makeText(mContext, R.string.NotConnect, Toast.LENGTH_LONG).show();
				        	 } else {
					        	 try{
					        		 if (actionTask == WorkServer.TASK_ADD)
					        			 mTask.settaskID(Integer.parseInt((String)result));
//					        		 Log.i(TAG, ">>>>>>>>>>>>>>>>>>>> " + (String)result);
					        	 } catch (NumberFormatException ex){
					        		 
					        	 }
//						        	 	getTasks();
					        	 	Toast.makeText(mContext, R.string.updateSuccess, Toast.LENGTH_SHORT).show();					        	 	
					        	 }
				         } else {
				        	 Toast.makeText(mContext, R.string.NotConnect, Toast.LENGTH_LONG).show();
				         }
			         }
			     }

				
			};
//				Object result = null;
			task.execute(action, null, null);

		}

	}

}
